<?php
/*
   Copyright 2011 BiSe Trojanov

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
 function sad_xml_getnode($node,$path){//$node as domNode
  if ('' ==$path){return $node;}
  if ('#'==$path){return $node->nodeValue;}

  preg_match('|^([a-z0-9.:_-]*)(\|[0-9]+)?(/?)(.*)|i',$path,$a);

  if ($a[1]==''){return NULL;}
  $k=(int)str_replace('|','',$a[2]);if ($k==0){$k=1;}
  for ($i=0;$i<$node->childNodes->length;$i++){
   $t=$node->childNodes->item($i);//FreeBSD patch
   if (preg_match('|^'.sad_safe_reg($a[1]).'$|i',$t->nodeName)){$k--;}
   if ($k==0){return sad_xml_getnode($node->childNodes->item($i),$a[4]);}
  }
  return NULL;
 }

 function sad_xml_get_all_nodes($node,$pattern){
  if ($node==NULL){return NULL;}
  $a=array();
  for ($i=0;$i<$node->childNodes->length;$i++){
   $t=$node->childNodes->item($i);
   if (preg_match('|^'.sad_safe_reg($pattern).'$|i',$t->nodeName)){
    array_push($a,$node->childNodes->item($i));
   }
  }
  return $a;
 }

 function sad_xml_attribute($node,$name){
  if ($node==NULL){return NULL;}
  if (!($node->hasAttributes())){return '';}
  foreach ($node->attributes as $attr){
   if (preg_match('|^'.sad_safe_reg($name).'$|i',$attr->nodeName)){return $attr->nodeValue;}
  }
  return '';
 }

 function sad_xml_rawtext($text){
  $xmlDoc = new DOMDocument('1.0', 'UTF-8');
  $xmlDoc->loadXML($text);
  $x = $xmlDoc->documentElement;
  return $x;
 }
 
 
 function sad_safe_xml($text,$u=true){
  $b=str_replace(']]>',']]]]><![CDATA[>',$text);
  if ($u){$b='<![CDATA['.$b.']]>';}
  return $b;
 }

 function sad_safe_xmlc($text,$u=true){
  while (preg_match('_\\-\\-_',$text)){$text=preg_replace('_\\-\\-_','- -',$text);}
  if ($u){$text='<!-- '.$text.' -->';}
  return $text;
 }
?>